// index.js
// 获取应用实例
const app = getApp()
import {
    util,
    Toast,
    Dialog,
    commonMixin
} from "../../utils/util.js";

function scrollNum(minNum, maxNum, top, start, end) {
    return start + ((top - minNum) / (maxNum - minNum) * (end - start));
}
Page({
    behaviors: [commonMixin],
    data: {
        sampleId: 0,
        orderSample: {
            status: 1
        },
        isLoad: false,
        showSetSampleSn: false,
        frameSampleSn: '',
        showAdress: false, //选择检测点
        showCheckTime: false, //选择检测时间
        showPopup: false,
        showCheckType: false,
        showChecker: false,
        showDoorAddress: false,
        showDoorPhone: false,
        selectCheckerIndex: '',
        selectCheckTimeIndex: '',
        selectCheckTypeIndex: 0,
        inputDoorAddress: '',
        inputDoorPhone: '',
        startDate: '',
        checkDate: '',
        doorAddress: '',
        doorPhone: '',
        stepIndex: 1, //当前是哪一步
        selectIndex: '', //选的那一个地点索引
        addressArray:[],
        checkerArray:[],
        checkTimeArray:[],
        isModify: false,
        dateModify: true,
        checkTypeArray:{
          1:'门店检测', 2:'上门检测'
        },
    },
    onCloseSetSampleSn() {
        this.setData({
            showSetSampleSn: !this.data.showSetSampleSn
        })
    },
    changeSampleSnInput(event) {
        this.setData({
            frameSampleSn: event.detail.value
        });
    },
    checkModify() {
      const checkDate = this.data.checkDate
      let result = false;
      console.log('checkDate', checkDate, 'status', this.data.orderSample.status)
      if (!checkDate || this.data.orderSample.status <= 2) {
        this.setData({
          dateModify: !result
        });
        return result;
      }
      const now = new Date();
      let tomorrow = new Date(now);
      tomorrow.setDate(now.getDate() + 1);
      tomorrow = this.formatDate(tomorrow);

      const checkDateObj = new Date(checkDate);

      const hours = now.getHours();
      const minutes = now.getMinutes();
      const seconds = now.getSeconds();

      const targetTime = new Date(tomorrow);
      targetTime.setHours(17, 0, 0, 0);

      result = checkDate < tomorrow ||
            (checkDate === tomorrow &&
            (hours > 17 || (hours === 17 && (minutes > 0 || seconds > 0))));
      this.setData({
        dateModify: !result
      });
      return result;
    },
    formatDate(d) {
      // 获取年、月、日
      let year = d.getFullYear();
      let month = String(d.getMonth() + 1).padStart(2, '0');
      let day = String(d.getDate()).padStart(2, '0');

      // 拼接成指定格式的字符串
      return `${year}-${month}-${day}`;
    },
    selectDate() {
      console.log('已超过修改时间')
      Toast('已超过修改时间');
    },
    handleBindSample() {
        this.submitSampleSn(this.data.frameSampleSn);
    },
    handleCheck() {
      util.http.post("v1/mini/sample-write-off",{
          sample_sn: this.data.orderSample.sample_sn
      }).then((res) => {
          if (res.data.code == 0) {
              // Toast('确认检测！');
              if (this.data.sampleId) {
                this.getSample();
              }
          } else {
              Toast(res.data.message);
          }
          wx.hideLoading();
      }).catch((err) => {
          wx.hideLoading();
          Toast('网络异常！刷新后重试！');
          console.log(err)
      })
    },
    openDoorAddress() {
      this.setData({
        showDoorAddress: true,
        inputDoorAddress: this.data.doorAddress
      });
    },
    openDoorPhone() {
      if (this.checkModify()) {
        this.selectDate();
        return;
      }
      this.setData({
        showDoorPhone: true,
        inputDoorPhone: this.data.doorPhone
      });
    },
    handleDoorAddressInput(e) {
      this.setData({
        inputDoorAddress: e.detail.value,
      })
    },
    handleDoorPhoneInput(e) {
      this.setData({
        inputDoorPhone: e.detail.value,
      })
    },
    onShowDoorAddressClose() {
      this.setData({
        showDoorAddress: false
      })
    },
    onShowDoorPhoneClose(action) {
      if (action.detail == 'confirm') {
        if (!this.handleDoorPhoneConfirm()) {
          return false;
        }
      }
      return true;
      // this.setData({
      //   showDoorPhone: false
      // })
    },
    handleDoorAddressConfirm() {
      this.setData({
        doorAddress: this.data.inputDoorAddress,
        showDoorAddress: false
      })
      util.http.post("v1/mini/sample-set-door-address",{
        id: this.data.orderSample.id,
        door_address: this.data.doorAddress
      }).then((res) => {
          if (res.data.code == 0) {

          } else {
              Toast(res.data.message);
          }
          wx.hideLoading();
      }).catch((err) => {
          wx.hideLoading();
          Toast('网络异常！刷新后重试！');
          console.log(err)
      })
    },
    validatePhoneNumber(phoneNumber) {
      const phoneRegex = /^1[3-9]\d{9}$/;
      return phoneRegex.test(phoneNumber);
    },
    handleDoorPhoneConfirm() {
      if (!this.validatePhoneNumber(this.data.inputDoorPhone)) {
        Toast('手机号码格式不正确！');
        // setTimeout(() => {
        //   this.setData({
        //     showDoorPhone: true
        //   })
        // }, 200);
        return false;
      }
      this.setData({
        doorPhone: this.data.inputDoorPhone,
        showDoorPhone: false
      })
      util.http.post("v1/mini/sample-set-door-phone",{
        id: this.data.orderSample.id,
        door_phone: this.data.doorPhone
      }).then((res) => {
          if (res.data.code == 0) {

          } else {
              Toast(res.data.message);
          }
          wx.hideLoading();
      }).catch((err) => {
          wx.hideLoading();
          Toast('网络异常！刷新后重试！');
          console.log(err)
      })
      return true;
    },
    submitSampleSn(sampleSn) {
        wx.showLoading({
            title: '加载中',
        })
        util.http.post("v1/mini/sample-bind-user",{
            sample_sn: sampleSn
        }).then((res) => {
            if (res.data.code == 0) {
                // if (!this.isModify) Toast('绑定成功！');
                this.setData({
                    sampleId: res.data.data.id,
                    showSetSampleSn: false,
                });
                this.getSample();
            } else {
                Toast(res.data.message);
                this.setData({
                    showSetSampleSn: false,
                });
            }
            wx.hideLoading();
        }).catch((err) => {
            wx.hideLoading();
            Toast('网络异常！刷新后重试！');
            console.log(err)
        })
    },
    selectCheckType() {
      this.setData({
        showCheckType: true
      })
    },
    selectCheckTypeNode(e) {
      let index = e.currentTarget.dataset.index;
      this.setData({
          selectCheckTypeIndex: index,
          showCheckType: false,
      });
      util.http.post("v1/mini/sample-set-check-type",{
          id: this.data.orderSample.id,
          check_type: index
      }).then((res) => {
          if (res.data.code == 0) {
          } else {
              Toast(res.data.message);
          }
          wx.hideLoading();
      }).catch((err) => {
          wx.hideLoading();
          Toast('网络异常！刷新后重试！');
          console.log(err)
      })
    },
    selectCheckNode(e) {
        let index = e.currentTarget.dataset.index;
        this.setData({
            selectCheckerIndex: index,
            showChecker: false,
        });
        util.http.post("v1/mini/sample-set-checker",{
            id: this.data.orderSample.id,
            checker_id: this.data.checkerArray[index].id
        }).then((res) => {
            if (res.data.code == 0) {
              this.setData({
                doorPhone: res.data.data.door_phone
              });
            } else {
                Toast(res.data.message);
            }
            wx.hideLoading();
        }).catch((err) => {
            wx.hideLoading();
            Toast('网络异常！刷新后重试！');
            console.log(err)
        })
    },
    selectCheckTimeNode(e) {
        let index = e.currentTarget.dataset.index;
        this.setData({
            selectCheckTimeIndex: index,
            showCheckTime: false,
        });
        util.http.post("v1/mini/sample-set-check-time",{
            id: this.data.orderSample.id,
            check_time_id: this.data.checkTimeArray[index].id
        }).then((res) => {
            if (res.data.code == 0) {

            } else {
                Toast(res.data.message);
            }
            wx.hideLoading();
        }).catch((err) => {
            wx.hideLoading();
            Toast('网络异常！刷新后重试！');
            console.log(err)
        })
    },
    selectNode(e) {
        let index = e.currentTarget.dataset.index;
        this.setData({
            selectIndex: index,
            showAdress: false,
        });
        util.http.post("v1/mini/sample-set-test-location",{
            id: this.data.orderSample.id,
            test_location_id: this.data.addressArray[index].id
        }).then((res) => {
            if (res.data.code == 0) {

            } else {
                Toast(res.data.message);
            }
            wx.hideLoading();
        }).catch((err) => {
            wx.hideLoading();
            Toast('网络异常！刷新后重试！');
            console.log(err)
        })
    },
    //关闭选择弹框
    onClose() {
        this.setData({
            showAdress: false
        })
    },
    onCheckerClose() {
      this.setData({
          showChecker: false
      })
    },
    onCheckTimeClose() {
      this.setData({
          showCheckTime: false
      })
    },
    onCheckTypeClose() {
      this.setData({
          showCheckType: false
      })
    },
    selectChecker() {
      if (this.checkModify()) {
        this.selectDate();
        return;
      }
        this.setData({
            showChecker: true
        })
    },
    selectCheckTime() {
      if (this.checkModify()) {
        this.selectDate();
        return;
      }
        this.setData({
            showCheckTime: true
        })
    },
    selectCheckDate() {
      if (this.checkModify()) {
        this.selectDate();
        return false;
      }
      return true;
    },
    handlePreviewQrcode(event) {
        wx.previewImage({
            urls: [event.currentTarget.dataset.url]
        })
    },
    selectAdress() {
      if (this.checkModify()) {
        this.selectDate();
        return;
      }
      this.setData({
          showAdress: true
      })
    },
    //去车型详情
    moveToModel(e) {
        let {
            index,
            id
        } = e.currentTarget.dataset;
        wx.navigateTo({
            url: '/pages/model/model-detail/index?id=' + id
        })
    },
    handleScanQrcode() {
        wx.scanCode({  
            success: (res) => {  
                if (res.result.indexOf('https://wechat.lychix.com/s/') != -1) {
                    let sampleSn = res.result.replace('https://wechat.lychix.com/s/', '');
                    this.submitSampleSn(sampleSn);
                }
            },  
            fail: function (err) {  
                Toast('扫码出错！');
            }  
        });
    },
    onLoad(options) {
      const currentDate = new Date();
      const tomorrow = new Date(currentDate.getTime() + 24 * 60 * 60 * 1000);
      const year = tomorrow.getFullYear();
      const month = (tomorrow.getMonth() + 1).toString().padStart(2, '0');
      const day = tomorrow.getDate().toString().padStart(2, '0');
      this.setData({
        startDate: `${year}-${month}-${day}`
      });
      if (options.id) {
        this.setData({
          sampleId: options.id
        });
      } else if (options.sampleSn) {
        this.submitSampleSn(options.sampleSn);
      }
      if (options.is_modify) {
        this.setData({
          isModify: true
        });
      }
    },
    onShow() {
        if (this.data.sampleId) {
            this.getSample();
            console.log('onShow getSample');
        }
    },
    handleJumpMyFamily() {
        wx.navigateTo({
          url: '/pages/myfamily/index',
        })
    },
    getCheckers() {
        util.http.post("v1/mini/family-users",{}).then((res) => {
            if (res.data.code == 0) {
              this.setData({
                checkerArray: res.data.data,
                selectCheckerIndex: '',
              })
              for (let i = 0; i < res.data.data.length; i++) {
                  const checker = res.data.data[i];
                  if (checker.id == this.data.orderSample.checker_id) {
                    this.setData({
                        selectCheckerIndex: i,
                      })
                  }
              }
            }
        }).catch((err) => {
            wx.hideLoading();
            Toast('网络异常！刷新后重试！');
            console.log(err)
        })
    },
    bindCheckDateChange(e) {
      if (this.checkModify()) {
        this.selectDate();
        return;
      }
      this.setData({
        checkDate: e.detail.value
      })
      // this.checkModify();
      util.http.post("v1/mini/sample-set-check-date",{
          id: this.data.orderSample.id,
          check_date: this.data.checkDate
      }).then((res) => {
          if (res.data.code == 0) {

          } else {
              Toast(res.data.message);
          }
          wx.hideLoading();
      }).catch((err) => {
          wx.hideLoading();
          Toast('网络异常！刷新后重试！');
          console.log(err)
      })
    },
    getCheckTimes() {
        util.http.post("v1/mini/check-times",{}).then((res) => {
            if (res.data.code == 0) {
              this.setData({
                checkTimeArray: res.data.data,
                selectCheckTimeIndex: '',
              })
              for (let i = 0; i < res.data.data.length; i++) {
                  const checkTime = res.data.data[i];
                  if (checkTime.id == this.data.orderSample.check_time_id) {
                    this.setData({
                      selectCheckTimeIndex: i,
                    })
                  }
              }
            }
        }).catch((err) => {
            wx.hideLoading();
            Toast('网络异常！刷新后重试！');
            console.log(err)
        })
    },
    getTestLocations() {
        util.http.post("v1/mini/sample-get-test-locations", {}).then((res) => {
            if (res.data.code == 0) {
                this.setData({
                    addressArray: res.data.data,
                    selectIndex: '',
                })
                for (let i = 0; i < res.data.data.length; i++) {
                    const address = res.data.data[i];
                    if (address.id == this.data.orderSample.test_location_id) {
                      this.setData({
                          selectIndex: i,
                        })
                    }
                }
            } else {
                Toast(res.data.message);
            }
        }).catch((err) => {
            Toast('网络异常！刷新后重试！');
        })
    },
    handleShowSetSampleSn() {
        this.setData({
            showSetSampleSn: true,
            frameSampleSn: ''
        });
    },
    getSample() {
      console.log('getSample....');
      let id = this.data.sampleId;
      if (!this.data.isLoad) wx.showLoading({})
      util.http.post("v1/mini/sample-get-detail", {
          id: id,
      }).then((res) => {
          if (res.data.code == 0) {
              this.setData({
                  orderSample: res.data.data,
                  isLoad: true
              })
              this.setData({
                checkDate: res.data.data.check_date,
                doorAddress: res.data.data.door_address,
                doorPhone: res.data.data.door_phone,
                selectCheckTypeIndex: res.data.data.check_type,
              });
              this.checkModify();
              this.getCheckers();
              this.getTestLocations();
              this.getCheckTimes();
              // if (this.data.orderSample.status == 5) {
              //   setTimeout(() => {
              //     this.onShow();
              //   }, 5000)
              // }
          } else {
              Toast(res.data.message);
              wx.switchTab({
                url: '/pages/index/index',
              })
          }
          wx.hideLoading();
      }).catch((err) => {
          console.log(err);
          Toast('网络异常！刷新后重试！');
          wx.hideLoading();
      })
    },
    handleOpenPdf(event) {
        let url = event.currentTarget.dataset.url;
        util.openPdf(url);
    },
    bindscroll(e) {
        const {
            scrollTop
        } = e.detail;
        let bgColor = 'rgba(255,255,255,0)';
        let opacity = 1 + (scrollTop - 300) / 80;
        this.setData({
            bgColor: 'rgba(255,255,255,' + opacity + ')'
        })
    },
    onShareAppMessage() {

    },
})